package com.jasperframework.boot.file.controller;

import cn.hutool.core.io.FileUtil;
import com.jasperframework.boot.common.ResultData;
import com.jasperframework.boot.common.utils.FileSeparatorUtil;
import com.jasperframework.boot.file.service.FmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * <p>文件上传接口</p>
 *
 * @site https://miliqkdoc.motopa.cn/
 * @author daizhao
 * @date 2017/11/29 13:44
 */
@RestController
@Slf4j
@RequestMapping("/fmsf")
public class FmsController {

    @Autowired
    private FmsService fmsService;

    /**
     * 根路径
     */
    @Value("${fms.baseDir}")
    private String baseDir;

    @RequestMapping("/fileUploadForm")
    public String fileUploadForm() throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("<form action='fileUpload' method='post' enctype='multipart/form-data'>");
        sb.append("<input type='file' name='file'/>");
        sb.append("<input type='submit' name='submit'/>");
        sb.append("</form>");
        return sb.toString();
    }

    /**
     *
     * @param file   上传文件
     * @param folder 文件夹分类名称（例如：默认分类为根文件夹：''，头像分类：systemAvatar#1级子文件夹#2级子文件夹#...）
     * @return
     * @throws IOException
     */
    @PostMapping("/fileUpload")
    public ResultData fileUpload(@RequestParam("file") MultipartFile file, @RequestParam(value = "folder", defaultValue = "") String folder, @RequestParam(value = "useOriginNameAsPrefix", defaultValue = "false") boolean useOriginNameAsPrefix) throws IOException {
        String path = fmsService.saveFile(file.getOriginalFilename(), folder, useOriginNameAsPrefix, file.getBytes());
        return ResultData.success(path);
    }

    @PostMapping("/clear")
    public ResultData clear(@RequestParam(value = "folder", defaultValue = "") String folder){
        try{
            if(org.apache.commons.lang3.StringUtils.isBlank(folder)){
                return ResultData.fail("【/fmsf/clear】任务清空指定目录的子路径不能为空");
            }
            StringBuilder sFile = new StringBuilder();
            if(folder.contains("#")){
                sFile.append(baseDir + File.separator + "fmsf" +File.separator + folder.replace("#", File.separator));
            }else{
                sFile.append(baseDir + File.separator + "fmsf" +File.separator + folder);
            }
            String dir = FileSeparatorUtil.replaceFileSeparator(sFile.toString());
            //删除目录
            return FileUtil.isDirectory(dir) && FileUtil.del(dir)
                    ? ResultData.successMsg("任务清空目录成功")
                    : ResultData.failMsg("任务清空目录失败");
        }catch (Exception e){
            log.error("【/fmsf/clear】任务清空指定目录接口出现异常", e);
            return ResultData.fail("【/fmsf/clear】任务清空指定目录接口出现异常");
        }
    }

    @PostMapping("/deleteFile")
    public ResultData deleteFile(@RequestParam(value = "fileFullPath", defaultValue = "") String fileFullPath){
        try{
            if(org.apache.commons.lang3.StringUtils.isBlank(fileFullPath)){
                return ResultData.fail("【/fmsf/deleteFile】删除指定全路径的文件不能为空");
            }
            StringBuilder sFile = new StringBuilder();
            String filePath = FileSeparatorUtil.replaceFileSeparator(sFile.append(baseDir + File.separator + fileFullPath).toString());
            //删除目录
            return FileUtil.exist(filePath) && FileUtil.del(filePath)
                    ? ResultData.successMsg("删除指定全路径的文件成功")
                    : ResultData.failMsg("删除指定全路径的文件失败");
        }catch (Exception e){
            log.error("【/fmsf/deleteFile】删除指定全路径的文件接口出现异常", e);
            return ResultData.fail("【/fmsf/deleteFile】删除指定全路径的文件接口出现异常");
        }
    }

    protected void setHeaders(HttpServletResponse response, byte[] content, MediaType mediaType) throws IOException {
        response.setContentLength(content.length);
        if (mediaType != null) {
            response.setContentType(mediaType.toString());
        }
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
    }

    public MediaType getMediaType(ServletContext servletContext, String path) {
        MediaType mediaType = null;
        if (servletContext != null) {
            String mimeType = servletContext.getMimeType(path);
            if (StringUtils.hasText(mimeType)) {
                mediaType = MediaType.parseMediaType(mimeType);
            }
        }
        return mediaType;
    }
}
